package com.dataconver.controller;

import com.dataconver.config.DataSyncProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 同步状态监控控制器
 * 提供定时任务状态和配置信息的REST API
 */
@RestController
@RequestMapping("/api/sync")
public class SyncStatusController {

    @Autowired
    private DataSyncProperties dataSyncProperties;

    /**
     * 获取同步状态信息
     */
    @GetMapping("/status")
    public Map<String, Object> getSyncStatus() {
        Map<String, Object> status = new HashMap<>();
        
        LocalDateTime now = LocalDateTime.now();
        String currentTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        status.put("currentTime", currentTime);
        status.put("cronExpression", dataSyncProperties.getCron());
        status.put("nextExecutionTime", getNextExecutionTime());
        status.put("schedulerEnabled", dataSyncProperties.getScheduler().isEnabled());
        status.put("autoStart", dataSyncProperties.getScheduler().isAutoStart());
        status.put("manualSync", dataSyncProperties.getScheduler().isManualSync());
        status.put("batchSize", dataSyncProperties.getBatchSize());
        status.put("maxRetries", dataSyncProperties.getMaxRetries());
        status.put("retryDelay", dataSyncProperties.getRetryDelay());
        
        return status;
    }

    /**
     * 获取下次执行时间（简单计算，实际应该使用Cron解析器）
     */
    private String getNextExecutionTime() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime next8AM = now.withHour(8).withMinute(0).withSecond(0).withNano(0);
        
        if (now.isAfter(next8AM)) {
            next8AM = next8AM.plusDays(1);
        }
        
        return next8AM.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}
